package model

import (
	"github.com/go-xorm/xorm"
	"github.com/kataras/iris"
	"errors"
	"fmt"
	"server/bitkop/core"
	_ "github.com/go-sql-driver/mysql"
)

var MainDB *xorm.Engine

func init() {
	var err error
	dsn := core.BK.TOMLConfig.GetMainDBConfig().FormatDBDsn()
	MainDB, err = InitMainDB(dsn)
	if err != nil {
		panic(fmt.Sprintf("main database init error, msg: %s", err.Error()))
	}
}

// 初始化数据库信息
func InitMainDB(dsn string) (*xorm.Engine, error) {
	var err error
	var db = new(xorm.Engine)
	db, err = xorm.NewEngine("mysql", dsn)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("database init error, msg: %s", err.Error()))
	}

	iris.RegisterOnInterrupt(func() {
		db.Close()
	})
	return db, nil
}
